package com.luxuewen.sxa.utils;

import com.upyun.RestManager;
import com.upyun.UpYunUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author wen
 */
@Slf4j
@Component
@Configuration
public class UPYUtils {
    private static String bucket;
    @Value("${upy.bucket}")
    public void setBucket (String bucket) {
        UPYUtils.bucket = bucket;
    }

    private static String operator;
    @Value("${upy.operator}")
    public void setOperator (String operator) {
        UPYUtils.operator = operator;
    }

    private static String password;
    @Value("${upy.password}")
    public void setPassword (String password) {
        UPYUtils.password = password;
    }

    private static String domain;
    @Value("${upy.domain}")
    public void setDomain (String domain) {
        UPYUtils.domain = domain;
    }

    /**
     * 文件上传
     * @param file 文件
     * @return 上传后文件访问路径
     * @throws Exception
     */
    public static String upload (MultipartFile file) throws Exception {
        String trueFileName =file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString()+trueFileName;

        RestManager manager = new RestManager(bucket,operator,password);
        String str = "Hello RestManager";
        Map<String, String> params = new HashMap<>();
        // 设置待上传文件的 Content-MD5 值
        // 如果又拍云服务端收到的文件MD5值与用户设置的不一致，将回报 406 NotAcceptable 错误
        params.put(RestManager.PARAMS.CONTENT_MD5.getValue(), UpYunUtils.md5(file.getBytes()));

        // 设置待上传文件的"访问密钥"
        // 注意：
        // 仅支持图片空！，设置密钥后，无法根据原文件URL直接访问，需带URL后面加上（缩略图间隔标志符+密钥）进行访问
        // 举例：
        // 如果缩略图间隔标志符为"!"，密钥为"bac"，上传文件路径为"/folder/test.jpg"，
        // 那么该图片的对外访问地址为：http://空间域名 /folder/test.jpg!bac
//        params.put(RestManager.PARAMS.CONTENT_SECRET.getValue(), "bac");

        String path = "/ss/xw/file/" + fileName;
        // 上传图片
        Response result = manager.writeFile(path, file.getBytes(), params);
        if (result.isSuccessful()) {
            return domain + path;
        } else {
            // 上传失败
            throw new Exception("上传失败["+result.code()+"]: "+result.message());
        }
    }

    /**
     * 指定存储路径上传
     * @param file 上传的文件
     * @param path 指定路径
     * @return 上传后文件访问路径
     * @throws Exception
     */
    public static String upload (MultipartFile file, String path) throws Exception {
        String trueFileName =file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString()+trueFileName;

        RestManager manager = new RestManager(bucket,operator,password);
        String str = "Hello RestManager";
        Map<String, String> params = new HashMap<>();
        params.put(RestManager.PARAMS.CONTENT_MD5.getValue(), UpYunUtils.md5(file.getBytes()));

        path = path + fileName;
        // 上传图片
        Response result = manager.writeFile(path, file.getBytes(), params);
        if (result.isSuccessful()) {
            return domain + path;
        } else {
            // 上传失败
            throw new Exception("上传失败["+result.code()+"]: "+result.message());
        }
    }
}
